package com.bianmin.Controller;

import com.bianmin.Data.Result;
import com.bianmin.Data.ResultCode;
import com.bianmin.Mapper.QuantityRecordsMapper;
import com.bianmin.Mapper.UserMapper;
import com.bianmin.Model.Article;
import com.bianmin.Model.QuantityRecords;
import com.bianmin.Model.User;
import com.bianmin.coomen.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;


@RestController
@RequestMapping("api/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UtilController utilController;

    @Autowired
    private QuantityRecordsMapper quantityRecordsMapper;

    //登陆账号
    @PostMapping("login")
    public Result<Map<String, Object>> registerAndLogin(@RequestBody Map<String, String> map) {
        String code = map.get("code");
        String timeString = Util.currentTimeString();
        String icon = map.get("icon");
        String nickName = map.get("nickName");
        String phoneNumber = map.get("phoneNumber");
        String token = Util.randomString(32);

        String AppId = "wx5f32bbcfb7d7ad60";
        String AppSecret = "2357f855c2ff86f577d8875fad9cb613";
        String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", AppId, AppSecret, code);

        Map<String, Object> response = utilController.requestWeChatApi(url, "GET",null);
        System.out.println(response);
        if (response.containsKey("openid")) {
            String openId = response.get("openid").toString();
            String session_key = response.get("session_key").toString();
            boolean isExist = userMapper.userExist(openId);
            if (!isExist) {
                User user = new User();
                user.setOpenId(openId);
                user.setSessionKey(session_key);
                user.setCreateTime(timeString);
                user.setToken(token);
                user.setIcon(icon);
                user.setQuantity(0);
                user.setNickName(nickName);
                user.setPhoneNumber(phoneNumber);
                userMapper.insert(user);
            }
            //返回数据
            Map<String, Object> userData = userMapper.queryUserWith(openId);
            return Result.success(userData);
        } else {
            return Result.error(ResultCode.RC1003);
        }
    }

    //手机号登录
    @GetMapping("getPhoneNumber")
    public Result<Object> getPhoneNumber(String code) {
        String accessToken = utilController.getAccessToken();
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
        String p = String.format("{\"code\":\"%s\"}", code);
        Map<String, Object> result = utilController.requestWeChatApi(url, "POST",p);
        Map<String,Object> phoneInfoMap = (Map<String, Object>) result.get("phone_info");
        String phoneNumber = phoneInfoMap.get("phoneNumber").toString();
        if (phoneNumber != null) {
            User user = userMapper.queryUserWithPhoneNumber(phoneNumber);
            if (user == null) {
                Map<String,Object> map = new HashMap<>();
                map.put("isNew",true);
                map.put("phoneNumber",phoneNumber);
                return Result.success(map);
            }else{
                return Result.success(user);
            }
        }else{
            return Result.error(ResultCode.RC1006);
        }

    }

    //使用token登陆
    @PostMapping("tokenLogin")
    public Result<User> loginWithToken(@RequestBody Map<String, String> map) {
        String token = map.get("token");
        User user = userMapper.queryUserWithToken(token);
        return Result.success(user);
    }

    //根据用户id获取用户信息
    @PostMapping("userById")
    public Result<User> queryUserWithUserId(@RequestBody Map<String,Object> map) {
        String userId = map.get("userId").toString();
        System.out.println(userId);
        User user = userMapper.queryUserWithUserId(Integer.parseInt(userId));
        return Result.success(user);
    }

    //我的发布
    @GetMapping("mySend")
    public Result<List<Article>> mySend(String userId) {
        return Result.success(userMapper.myArticle(userId));
    }

    //我的回复
    @GetMapping("myRepay")
    public Result<List<Map<String, Object>>> getMyRepay(String userId, int page, int pageSize) {
        page = page  * pageSize;
        List<Map<String, Object>> maps = userMapper.queryMyRepayWithUserId(userId, page, pageSize);
        return Result.success(maps);
    }

    //更新用户信息
    @PostMapping("updateUserInfo")
    public Result updateUserInfo(@RequestBody User user) {
        int id = user.getId();
        User queryUser = userMapper.queryUserWithUserId(id);
        if (user.getNickName() != null) {
            queryUser.setNickName(user.getNickName());
        }
        if (user.getIcon() != null) {
            queryUser.setIcon(user.getIcon());
        }
        if (user.getPhoneNumber() != null) {
            queryUser.setPhoneNumber(user.getPhoneNumber());
        }

        int r = userMapper.updateById(queryUser);
        Map<String,String> result = new HashMap<>();
        result.put("icon",queryUser.getIcon());
        result.put("nickName",queryUser.getNickName());
        return r == 1 ? Result.success(result) : Result.error(ResultCode.RC1001);
    }

    //获取收藏列表
    @GetMapping("collectionList")
    public Result<List<Map<String,Object>>> getCollectionList(String userId , int page , int pageSize) {
        page = page * pageSize;
        List<Map<String, Object>> maps = userMapper.queryCollectionList(userId, page, pageSize);
        return Result.success(maps);
    }

    //查询积分操作记录
    @GetMapping("quantityRecords")
    public Result<List<QuantityRecords>>  userQuantityRecords(Integer userId, int page, int pageSize) {
        page = page * pageSize;
        List<QuantityRecords> quantityRecords = quantityRecordsMapper.queryUserRecords(userId, page, pageSize);
        return Result.success(quantityRecords);
    }


}
